package org.springsecuritylearn.repository.jvm.lession1.demo1;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

/** 虚引用测试
 * @author hyf
 * @Title: ${file_name}
 * @Package org.springsecuritylearn.repository.jvm.lession1.demo1
 * @Description: ${todo}
 * @date 2018/5/5下午5:17
 */
public class TraceCanReliveObj {
    public static TraceCanReliveObj obj;

    static ReferenceQueue<TraceCanReliveObj> phantomQueue=null;
    public static class CheckRefQueue extends Thread{
        @Override
        public void run() {
            while(true){
                if(phantomQueue!=null){
                    PhantomReference<TraceCanReliveObj> obj=null;
                    try {
                        obj= (PhantomReference<TraceCanReliveObj>) phantomQueue.remove();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (obj!=null){
                        System.out.println("TraceCanReliveObj is delete");
                    }
                }
            }
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("CanReliveObj finalize called");
        obj=this;
    }

    @Override
    public String toString() {
        return "i am TraceCanReliveObj{}";
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t=new  CheckRefQueue();
        t.setDaemon(true);
        t.start();

        phantomQueue=new ReferenceQueue<TraceCanReliveObj>();
        Thread.sleep(1000);
        obj=new TraceCanReliveObj();
        PhantomReference<TraceCanReliveObj> phantomReference=new PhantomReference<TraceCanReliveObj>(obj,phantomQueue);
        obj=null;
        System.gc();
        Thread.sleep(1000);
        if (obj==null){
            System.out.println("1 obj 是 null");
        }else {
            System.out.println("1 obj 不是 null");
        }
        System.out.println("第二次GC");
        obj=null;
        System.gc();
        Thread.sleep(1000);
        if (obj==null){
            System.out.println("2 obj 是 null");
        }else {
            System.out.println("2 obj 不是 null");
        }


    }
}
